package app.framework.front.util;

import cn.hutool.core.io.IoUtil;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.ErrorUtil;
import jasmine.framework.common.util.JsonUtil;
import jasmine.framework.common.util.StringUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * <p>
 * 扫描前端相关资源。
 * </p>
 *
 * @author mh.z
 */
public class FrontScanUtil {

    /**
     * 扫描页面配置
     *
     * @param locationPattern
     * @return
     */
    public static List<PageConfig> scanPageConfigs(String locationPattern) {
        CheckUtil.notNull(locationPattern, "locationPattern null");

        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
        List<PageConfig> resultList = new ArrayList<>();

        try {
            // 查找页面配置
            Resource[] resources = pathResolver.getResources(locationPattern);

            for (Resource resource : resources) {
                String configContent;

                // 读取页面配置内容
                try (InputStream inputStream = resource.getInputStream()) {
                    configContent = IoUtil.readUtf8(inputStream);
                }

                if (StringUtil.isNotBlank(configContent)) {
                    List<PageConfig> configList = JsonUtil.fromArray(configContent, PageConfig.class);
                    // 添加页面配置信息到返回结果中
                    resultList.addAll(configList);
                }
            }
        } catch (IOException e) {
            throw ErrorUtil.sneakyError(e);
        }

        return resultList;
    }

    /**
     * 扫描多语言资源
     *
     * @param locationPattern
     * @return
     */
    public static Properties scanI18nResources(String locationPattern) {
        CheckUtil.notNull(locationPattern, "locationPattern null");

        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
        Properties properties = new Properties();

        try {
            // 查找多语言资源
            Resource[] resources = pathResolver.getResources(locationPattern);

            for (Resource resource : resources) {
                try (InputStream inputStream = resource.getInputStream()) {
                    try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
                        // 添加多语言到返回结果中
                        properties.load(reader);
                    }
                }
            }
        } catch (IOException e) {
            throw ErrorUtil.sneakyError(e);
        }

        return properties;
    }

}
